<template>
  <div class="log-list-container">
    <div class="page-header">
      <h2>操作日志</h2>
    </div>
    
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="操作人">
          <el-input v-model="searchForm.operator" placeholder="请输入操作人" clearable />
        </el-form-item>
        
        <el-form-item label="操作模块">
          <el-select v-model="searchForm.module" placeholder="请选择模块" clearable>
            <el-option v-for="item in moduleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operation" placeholder="请选择操作类型" clearable>
            <el-option v-for="item in operationOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.date_range"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card shadow="never" class="table-card">
      <div class="table-operations">
        <el-button type="danger" @click="handleClear">清空日志</el-button>
        <el-button type="primary" @click="handleExport">导出日志</el-button>
      </div>
      
      <el-table :data="logList" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="module" label="操作模块" width="120">
          <template #default="scope">
            {{ getModuleText(scope.row.module) }}
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作类型" width="120">
          <template #default="scope">
            {{ getOperationText(scope.row.operation) }}
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="detail" label="操作详情" min-width="200" show-overflow-tooltip />
        <el-table-column prop="create_time" label="操作时间" width="180" sortable />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="日志详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作人">{{ currentLog.operator }}</el-descriptions-item>
        <el-descriptions-item label="操作模块">{{ getModuleText(currentLog.module) }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ getOperationText(currentLog.operation) }}</el-descriptions-item>
        <el-descriptions-item label="操作状态">
          <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'">
            {{ currentLog.status === 'success' ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentLog.create_time }}</el-descriptions-item>
        <el-descriptions-item label="操作详情" :span="2">
          {{ currentLog.detail }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template v-if="currentLog.request_data || currentLog.response_data">
        <el-divider content-position="left">请求/响应数据</el-divider>
        
        <el-tabs>
          <el-tab-pane v-if="currentLog.request_data" label="请求数据">
            <pre class="code-block">{{ formatJson(currentLog.request_data) }}</pre>
          </el-tab-pane>
          <el-tab-pane v-if="currentLog.response_data" label="响应数据">
            <pre class="code-block">{{ formatJson(currentLog.response_data) }}</pre>
          </el-tab-pane>
        </el-tabs>
      </template>
      
      <template v-if="currentLog.error_message">
        <el-divider content-position="left">错误信息</el-divider>
        <pre class="code-block error">{{ currentLog.error_message }}</pre>
      </template>
    </el-dialog>
    
    <!-- 清空日志确认对话框 -->
    <el-dialog v-model="clearDialogVisible" title="警告" width="400px">
      <div class="clear-confirm">
        <el-alert
          title="此操作将永久清空所有操作日志，是否继续？"
          type="warning"
          :closable="false"
          show-icon
        />
        
        <div class="date-picker-container">
          <span>选择清空日期范围：</span>
          <el-date-picker
            v-model="clearDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%; margin-top: 10px;"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClear" :loading="submitting">确认清空</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'LogList',
  setup() {
    const loading = ref(false)
    const submitting = ref(false)
    const logList = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const detailDialogVisible = ref(false)
    const clearDialogVisible = ref(false)
    const clearDateRange = ref([])
    const currentLog = reactive({})
    
    // 模块选项
    const moduleOptions = [
      { label: '用户管理', value: 'user' },
      { label: '场馆管理', value: 'venue' },
                  { label: '活动管理', value: 'activity' },
      { label: '支付管理', value: 'payment' },
      { label: '系统管理', value: 'system' }
    ]
    
    // 操作类型选项
    const operationOptions = [
      { label: '登录', value: 'login' },
      { label: '登出', value: 'logout' },
      { label: '查询', value: 'query' },
      { label: '新增', value: 'create' },
      { label: '修改', value: 'update' },
      { label: '删除', value: 'delete' },
      { label: '导出', value: 'export' },
      { label: '导入', value: 'import' }
    ]
    
    // 状态选项
    const statusOptions = [
      { label: '成功', value: 'success' },
      { label: '失败', value: 'fail' }
    ]
    
    // 搜索表单
    const searchForm = reactive({
      operator: '',
      module: '',
      operation: '',
      status: '',
      date_range: [],
      start_time: '',
      end_time: ''
    })
    
    // 处理日期变化
    const handleDateChange = (val) => {
      if (val) {
        searchForm.start_time = val[0]
        searchForm.end_time = val[1]
      } else {
        searchForm.start_time = ''
        searchForm.end_time = ''
      }
    }
    
    // 获取日志列表
    const fetchLogList = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          page_size: pageSize.value,
          operator: searchForm.operator,
          module: searchForm.module,
          operation: searchForm.operation,
          status: searchForm.status,
          start_time: searchForm.start_time,
          end_time: searchForm.end_time
        }
        
        const response = await request.get('/v1/admin/logs', { params })
        logList.value = response.data.items || []
        total.value = response.data.total || 0
      } catch (error) {
        console.error('获取日志列表失败', error)
        ElMessage.error('获取日志列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchLogList()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = key === 'date_range' ? [] : ''
      })
      handleSearch()
    }
    
    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchLogList()
    }
    
    // 每页条数变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchLogList()
    }
    
    // 查看日志详情
    const handleDetail = (row) => {
      Object.assign(currentLog, row)
      detailDialogVisible.value = true
    }
    
    // 清空日志
    const handleClear = () => {
      clearDateRange.value = []
      clearDialogVisible.value = true
    }
    
    // 确认清空日志
    const confirmClear = async () => {
      submitting.value = true
      try {
        const params = {}
        if (clearDateRange.value && clearDateRange.value.length === 2) {
          params.start_date = clearDateRange.value[0]
          params.end_date = clearDateRange.value[1]
        }
        
        await request.delete('/v1/admin/logs', { params })
        ElMessage.success('清空日志成功')
        clearDialogVisible.value = false
        fetchLogList()
      } catch (error) {
        console.error('清空日志失败', error)
        ElMessage.error('清空日志失败')
      } finally {
        submitting.value = false
      }
    }
    
    // 导出日志
    const handleExport = async () => {
      try {
        const params = {
          operator: searchForm.operator,
          module: searchForm.module,
          operation: searchForm.operation,
          status: searchForm.status,
          start_time: searchForm.start_time,
          end_time: searchForm.end_time
        }
        
        const response = await request.get('/v1/admin/logs/export', { 
          params,
          responseType: 'blob'
        })
        
        // 创建下载链接
        const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `操作日志_${new Date().toISOString().split('T')[0]}.xlsx`
        link.click()
        URL.revokeObjectURL(link.href)
        
        ElMessage.success('导出日志成功')
      } catch (error) {
        console.error('导出日志失败', error)
        ElMessage.error('导出日志失败')
      }
    }
    
    // 获取模块文本
    const getModuleText = (module) => {
      const found = moduleOptions.find(item => item.value === module)
      return found ? found.label : module
    }
    
    // 获取操作类型文本
    const getOperationText = (operation) => {
      const found = operationOptions.find(item => item.value === operation)
      return found ? found.label : operation
    }
    
    // 格式化JSON
    const formatJson = (json) => {
      if (!json) return ''
      
      try {
        if (typeof json === 'string') {
          json = JSON.parse(json)
        }
        return JSON.stringify(json, null, 2)
      } catch (e) {
        return json
      }
    }
    
    onMounted(() => {
      fetchLogList()
    })
    
    return {
      loading,
      submitting,
      logList,
      moduleOptions,
      operationOptions,
      statusOptions,
      searchForm,
      currentPage,
      pageSize,
      total,
      detailDialogVisible,
      clearDialogVisible,
      clearDateRange,
      currentLog,
      handleDateChange,
      handleSearch,
      resetSearch,
      handleCurrentChange,
      handleSizeChange,
      handleDetail,
      handleClear,
      confirmClear,
      handleExport,
      getModuleText,
      getOperationText,
      formatJson
    }
  }
}
</script>

<style lang="scss" scoped>
.log-list-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-operations {
      margin-bottom: 15px;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .code-block {
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 10px;
    font-family: monospace;
    white-space: pre-wrap;
    word-break: break-all;
    max-height: 300px;
    overflow-y: auto;
    
    &.error {
      background-color: #fef0f0;
      color: #f56c6c;
    }
  }
  
  .clear-confirm {
    .date-picker-container {
      margin-top: 20px;
    }
  }
}
</style> 